# -*- coding: utf-8 -*-
# @Author: liuzhen
# @Date:   2018-07-18 12:59:42
# @Last Modified by:   liuzhen
# @Last Modified time: 2018-07-19 12:54:37
import os
import sys
import platform
import pymel.core as pmc
import maya.cmds as cmds
import maya.mel as mel
import xgenm as xg
import xgenm.xmaya.xgmExternalAPI as xgmExternalAPI
from mtoa.core import createStandIn
import json
import datetime

start_frame = str(pmc.playbackOptions(q=1,min=1))  
end_frame = str(pmc.playbackOptions(q=1,max=1))  
X = os.sep
parent = X.join(str(pmc.sceneName()).split(X)[:-1])  
jiuqianpath = "/mnt/data/liuzhen/test/0607/cache" 
jiuqian_projectpath = os.environ["JIUQIAN_PROJECT"]

def export_reference_list(basepath) :  
    print "asdasdasd"
    lista = pmc.ls(type="reference")
    ref_list = []
    for i in lista :   
        try :  
            path = i.fileName(True, False, False)
            ref_list.append(path)
        except :  
            pass
    texts = "\n".join(ref_list)
    file_path = basepath + X + os.path.basename(nodeControl.parent) + X +"reference.txt"
    fl=open(file_path, 'a+')  
    fl.write(texts)
    fl.close()

def get_all_children(parents, listx) :  
    for parentx in parents :  
        for child in parentx.listRelatives(c=True) :  
            listx.append(child)
            get_all_children(child.listRelatives(c=True), listx)

def export_material(basepath, dict_mat) :  
    output_dir = basepath + X + os.path.basename(nodeControl.parent) + X +"Material"  
    # output_path = output_dir + X + "_" + aihairnodee.split(":")[-1] + ".mb"
    output_path = output_dir + X + "_" + "HairShader" + ".mb"
    all_hairshader = []
    all_hairshader_Noreference = []
    if not os.path.exists(output_dir) :  
        os.makedirs(output_dir)
    else :  
        pass
    for key in dict_mat :  
        aihairnodee = cmds.listConnections(key, type="aiStandardHair")[0]
        # output_path = output_dir + X + "_" + aihairnodee.split(":")[-1] + ".mb"
        # a = 'file -typ "mayaBinary" -pr -es "%s"' % (output_path)
        node = pmc.PyNode(key)
        if node.isReferenced() :  
            new_shader = pmc.duplicate(aihairnodee)
            all_hairshader.append(new_shader)
            # pmc.mel.eval(a)  
        else :  
            all_hairshader_Noreference.append(aihairnodee)
    print "@#@#@#@#@#@#@#@#@#@"
    all_Hshader = all_hairshader + all_hairshader_Noreference
    pmc.select(all_Hshader)
    cmds.file("%s" % (output_path), exportSelected=True, type="mayaBinary", pr=True, es=True)  
    for new in all_hairshader :  
        pmc.delete(new) 
    f = open(output_dir + X + "manifests.json", 'w')  
    new_dict = {}
    for key in dict_mat :  
        new_dict[key] = str(dict_mat[key])
    json_str = json.dumps(new_dict, indent=4)
    f.write(str(json_str))
    f.close()

def show_xgen_list() :  
    pass

def get_xgen_dict() :  
    xgen_dict = {}
    xgen_list = ["xgmSplineDescription", "xgmDescription"]
    hshader = cmds.ls(type="aiStandardHair")
    # get all xgen
    se_list = [x for i in hshader for x in cmds.listConnections(i, type = "shadingEngine")]
    xgen_a = [v for o in se_list for v in pmc.listConnections(o, type=xgen_list, sh=True)]
    for i in se_list :  
        xgen_dict[i] = pmc.listConnections(i, type=xgen_list, sh=True)
    print xgen_dict
    return xgen_dict

def xgen_old_exist(xgen_dict) :  
    all_xgen = [xgen for key in xgen_dict for xgen in xgen_dict[key]]
    all_type_list = [x.type() for x in all_xgen]
    return all_xgen



def get_hair_material() :  
    aihair_material_dict = {}
    all_aihair = pmc.ls(type="aiStandardHair")
    # print all_aihair
    if len(all_aihair) :  
        for hair_mat in all_aihair :  

            if len(hair_mat.listConnections(type="shadingEngine")) :  
                mat_SE = hair_mat.listConnections(type="shadingEngine")[0]
                matname = pmc.PyNode(hair_mat).name()
                if pmc.PyNode(mat_SE).listConnections(type=['xgmDescription', 'xgmSplineDescription'], shapes=True) != [] :  
                    nodename = [pmc.PyNode(i).name() for i in pmc.PyNode(mat_SE).listConnections(type=['xgmDescription', 'xgmSplineDescription'], shapes=True)]
                    aihair_material_dict[matname] = nodename
    # print aihair_material_dict
    return aihair_material_dict

def old_xgen2patches() :  
    strCurrentScene = cmds.file(q=True, sn=True)
    strSceneName = ""
    if strCurrentScene:
        strScenePath = os.path.dirname(strCurrentScene)
        strSceneFile = os.path.basename(strCurrentScene)
        strSceneName = os.path.splitext(strSceneFile)[0];
    else:
        xg.XGError(maya.stringTable['y_xgDescriptionEditor.kYouMustSaveTheSceneFirst'])
    ExportStartFrame = float(pmc.playbackOptions(q=1, min=1))
    ExportEndFrame = float(pmc.playbackOptions(q=1, max=1))
    cmdAlembicBase = 'AbcExport -j "'
    # Anim = dialog.getAnim()
    cmdAlembicBase = cmdAlembicBase + '-frameRange ' + str(ExportStartFrame) + ' ' + str(ExportEndFrame)
    cmdAlembicBase = cmdAlembicBase + ' -uvWrite -attrPrefix xgen -worldSpace'
    palette = cmds.ls(exactType="xgmPalette")
    for p in range(len(palette)):
        filename = strScenePath + X + strSceneName + "__" + xgmExternalAPI.encodeNameSpace(str(palette[p])) + ".abc"
        descShapes = cmds.listRelatives(palette[p], type="xgmDescription", ad=True)
        cmdAlembic = cmdAlembicBase
        for d in range(len(descShapes)):
            descriptions = cmds.listRelatives(descShapes[d], parent=True)
            if len(descriptions):
                patches = xg.descriptionPatches(descriptions[0])
                for patch in patches:
                    cmd = 'xgmPatchInfo -p "' + patch + '" -g';
                    geom = mel.eval(cmd)
                    geomFullName = cmds.ls(geom, l=True)
                    cmdAlembic += " -root " + geomFullName[0]
        cmdAlembic = cmdAlembic + ' -stripNamespaces -file \'' + filename + '\'";';
        print cmdAlembic
        print 'export xgen patches ...'
        mel.eval(cmdAlembic)  

def g_export_xgen(xgen_list, shadername, basepath, *args) :  

    if args == () :  
        new_xgen_list = [i for i in xgen_list if i.isVisible()]
        pmc.select(new_xgen_list, r=True)  
        pmc.arnoldExportAss(s=True, ep=False,  
                            sf=float(nodeControl.start_frame),  
                            ef=float(nodeControl.end_frame),  
                            a=True,
                            f=basepath + X + os.path.basename(nodeControl.parent) + X + "Assfile" + X + shadername + X + shadername,  
                            m=255)  
        print "export to " + basepath + X + os.path.basename(nodeControl.parent) + X + "Assfile" + X + shadername + X + shadername

    else :  
        new_xgen_list = [i for i in xgen_list if i.isVisible()]
        pmc.select(new_xgen_list, r=True)  
        pmc.arnoldExportAss(s=True, 
                            ep=False, 
                            sf=float(args[0]), 
                            ef=float(args[1]), 
                            a=True,
                            f=basepath + X + os.path.basename(nodeControl.parent) + X + "Assfile" + X + shadername + X + shadername, 
                            m=255)  
        print "export to " + basepath + X + os.path.basename(nodeControl.parent) + X + "Assfile" + X + shadername + X + shadername

    def getallreference(self) :  
        pmc.ls(type="reference")

def get_nodeInfo(basepath, normal_assDict) :  
    fileName = "Asset_list.json"  
    savePath = basepath + X + os.path.basename(nodeControl.parent)  
    fullpath = savePath + X + fileName  
    asset_dict = {}
    print fullpath
    if not os.path.exists(savePath) :  
        os.mkdir(savePath)
    else :  
        pass
    if not os.path.exists(fullpath) :  

        asset_file = open(fullpath, 'w')  
        for key in normal_assDict :  
            listx = normal_assDict[key]  
            for node in listx :  
                rnode = pmc.PyNode(node)
                if rnode.isReferenced() :  
                    asset_dict[rnode.name()] = "%s" % (str(rnode.referenceFile()))
        json_str = json.dumps(asset_dict, indent=4)
        asset_file.write(str(json_str))
        asset_file.close()

    else :    
        os.remove(fullpath)
        filex = open(fullpath, "w")
        # asset_dict = json.load(filex)  
        for key in normal_assDict :  
            listx = normal_assDict[key]  
            for node in listx :  
                rnode = pmc.PyNode(node)
                if rnode.isReferenced() :  
                    asset_dict[rnode.name()] = "%s" % (rnode.referenceFile())
        json_str = json.dumps(asset_dict, indent=4)
        filex.write(str(json_str))
        filex.close()

    print asset_dict

# -------------------------get all transform nodes

def getall_transformNode() :  
    asset_dict = {}  
    alltransform = pmc.ls(type = "transform")
    default_cam = ["front", "persp", "side", "top"]
    assetNode_lst = [node for node in alltransform if cmds.attributeQuery("asset_name", node=node.name(), exists=True)]  
    all_cloth = [cloth for cloth in alltransform if cmds.attributeQuery("clothCache", node=node.name(), exists=True)]
    print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

    charNode_lst = [node for node in assetNode_lst if node.getAttr("asset_type") == "c"]  
    propNode_list = [node for node in assetNode_lst if node.getAttr("asset_type") == "p"]  
    backNode_list = [node for node in assetNode_lst if node.getAttr("asset_type") == "b"]  
    vis_list = [i for i in cmds.ls(type="transform") if cmds.attributeQuery("Xgen", node=i, exists=True) or cmds.attributeQuery("xgen", node=i, exists=True)]  
    camNode_list = [node.listRelatives(parent=True)[0] for node in pmc.ls(type="camera", visible=True)]  
    print camNode_list

    asset_dict["char"] = charNode_lst  
    asset_dict["prop"] = propNode_list  
    asset_dict["background"] = backNode_list  
    asset_dict["camera"] = camNode_list  
    asset_dict["cloth"] = all_cloth
    asset_dict["vis"] = vis_list
    print asset_dict["camera"]

    return asset_dict  

def import_reference(filepath) :  
    fullpath = filepath
    nodes = cmds.file(fullpath, reference=True, ignoreVersion=True, returnNewNodes=True)
    return nodes

class nodeControl(object) :  

    start_frame = str(pmc.playbackOptions(q=1,min=1))  
    end_frame = str(pmc.playbackOptions(q=1,max=1))  
    parent = X.join(str(pmc.sceneName()).split(X)[:-1])  
    jiuqianpath = "/mnt/data/liuzhen/test/0607/cache" 

    def __init__(self, mayanode) :  
        self.node = mayanode  

    def __exportCamera(self, basepath, *args) :  
        origin_cam = self.node
        new_cam = pmc.duplicate(origin_cam, rr=True, un=True)  

        try :  
            pmc.disconnectAttr('%s_translateX.output' % (origin_cam), 
                               '%s.translate.translateX' % (new_cam[0]))  
        except :  
            pass  
        try :  
            pmc.disconnectAttr('%s_translateY.output' % (origin_cam), 
                               '%s.translate.translateY' % (new_cam[0]))  
        except :  
            pass  
        try :  
            pmc.disconnectAttr('%s_translateZ.output' % (origin_cam), 
                               '%s.translate.translateZ' % (new_cam[0]))  
        except :  
            pass  
        try :
            pmc.disconnectAttr('%s_rotateX.output' % (origin_cam), 
                               '%s.rotate.rotateX' % (new_cam[0]))  
        except :  
            pass  
        try :
            pmc.disconnectAttr('%s_rotateY.output' % (origin_cam), 
                               '%s.rotate.rotateY' % (new_cam[0]))  
        except :  
            pass  
        try :
            pmc.disconnectAttr('%s_rotateZ.output' % (origin_cam), 
                               '%s.rotate.rotateZ' % (new_cam[0]))  
        except :  
            pass  

        pmc.parentConstraint(origin_cam, new_cam[0], mo=True, weight=1)  
        if args == () :  
            pmc.bakeSimulation(new_cam, t=(float(nodeControl.start_frame),float(nodeControl.end_frame)), sb=1, pok=1, sac=0)  
            pmc.delete(new_cam[0].listRelatives(c=True, type="parentConstraint")[0])  
            root = "-root %s " % (new_cam[0])  
            output_dir = basepath + X + os.path.basename(nodeControl.parent) + X +"Camera"  
            output_path = output_dir + X + os.path.basename(nodeControl.parent) + "_" + new_cam[0] + ".abc"  
            command = "-frameRange " + nodeControl.start_frame + " " + nodeControl.end_frame + " "  + root + "-file " + output_path  
            if os.path.exists(X.join(output_path.split(X)[:-1])) :  
                cmds.AbcExport ( j = command )  
            else :  
                os.makedirs(X.join(output_path.split(X)[:-1]))  
                cmds.AbcExport ( j = command )  
            pmc.delete(new_cam)  
            print "Done directory : %s" % (output_path)  
        else :  
            pmc.bakeSimulation(new_cam, t=(args[0],args[1]), sb=1, pok=1, sac=0)  

            pmc.delete(new_cam[0].listRelatives(c=True, type="parentConstraint")[0])  
            root = "-root %s " % (new_cam[0])  
            output_dir = basepath + X + os.path.basename(nodeControl.parent) + X +"Camera"  
            output_path = output_dir + X + os.path.basename(nodeControl.parent) + "_" + new_cam[0] + ".abc"  
            command = "-frameRange " + args[0] + " " + args[1] + " "  + root + "-file " + output_path  
            if os.path.exists('/'.join(output_path.split('/')[:-
                1])) :  
                cmds.AbcExport ( j = command )  
            else :  
                os.makedirs('/'.join(output_path.split('/')[:-1]))  
                cmds.AbcExport ( j = command )  
            pmc.delete(new_cam)  
            print "Done directory : %s" % (output_path)  

    def __exportAbc(self, basepath, mtype, *args) :  
        model_node = self.node
        namewithnamespace = "_".join(model_node.name().split(":"))
        name = model_node.getAttr("asset_type") + model_node.getAttr("asset_name")  
        geometry_node = model_node.listRelatives(c=True)[0]
        root = "-root %s " % (model_node)  
        setting = "-uvWrite -writeFaceSets -worldSpace -writeVisibility -writeUVSets -dataFormat ogawa "  
        output_dir = basepath + X + os.path.basename(nodeControl.parent) + X + mtype + X + namewithnamespace
        output_path = output_dir + X + os.path.basename(nodeControl.parent) + "_" + name + ".abc" 
        print output_path

        if args == () :  
            command = "-frameRange " + nodeControl.start_frame + " " + nodeControl.end_frame + " " + setting + root + "-file " + output_path  
            if os.path.exists(output_dir) :  
                cmds.AbcExport ( j = command )  
            else :  
                os.makedirs(output_dir)  
                cmds.AbcExport ( j = command )  
            print "export to %s" % (output_path)
        else :  
 
            command = "-frameRange " + args[0] + " " + args[1] + " " + setting + root + "-file " + output_path  
            print output_path
            if os.path.exists(output_dir) :  
                cmds.AbcExport ( j = command )  
            else :  
                os.makedirs(output_dir)  
                cmds.AbcExport ( j = command )  
            print "export to %s" % (output_path)


    def __exportCloth(self, basepath, mtype, *args) :  
        model_node = self.node
        name = model_node.getAttr("asset_type") + model_node.getAttr("asset_name")  
        geometry_node = model_node.listRelatives(c=True)[0]
        children_list = []
        get_all_children(model_node.listRelatives(c=True), children_list)
        cloth_list = []
        for child in children_list :  
            if child.hasAttr("clothCache") :  
                cloth_list.append(child.name())
        root = "-root %s " % (geometry_node)  
        setting = "-uvWrite -writeFaceSets -worldSpace -writeVisibility -writeUVSets -dataFormat ogawa "  
        output_dir = basepath + X + os.path.basename(nodeControl.parent) + X + mtype + X + name
        output_path = output_dir + X + os.path.basename(nodeControl.parent) + "_" + name + "_cloth" + ".abc"  
        children = [child for child in geometry_node.listRelatives(c=True)]  
        cloth_group = []
        for child in children :  
            if len(child.split("_")) > 3 and child.split("_")[-2] == "clothCache" :  
                cloth_group.append(child)
            else :  
                pass
        if cloth_list != [] :  
            full_path_list = [pmc.PyNode(cloth).fullPath() for cloth in cloth_list]
            root_command = " -root ".join(full_path_list)
            # print root_command
            cloth_root = "-root %s " % (root_command)  
            print cloth_root
            clothoutput_path = output_path
            cloth_command = "-frameRange " + nodeControl.start_frame + " " + nodeControl.end_frame + " " + setting + cloth_root + "-file " + output_path  
            print cloth_command
            if args == () :  
                if os.path.exists(output_dir) :  
                    cmds.AbcExport ( j = cloth_command )  
                else :  
                    os.makedirs(output_dir)  
                    cmds.AbcExport ( j = cloth_command )  

            else :  
                cloth_command = "-frameRange " + args[0] + " " + args[1] + " " + setting + cloth_root + "-file " + output_path  
                print output_path
                if os.path.exists(output_dir) :  
                    cmds.AbcExport ( j = cloth_command )  
                else :  
                    os.makedirs(output_dir)  
                    cmds.AbcExport ( j = cloth_command )  
                print "export to %s" % (output_path)

    @staticmethod
    def old_xgen2patches() :  
        strCurrentScene = cmds.file(q=True, sn=True)
        strSceneName = ""
        if strCurrentScene:
            strScenePath = os.path.dirname(strCurrentScene)
            strSceneFile = os.path.basename(strCurrentScene)
            strSceneName = os.path.splitext(strSceneFile)[0];
        else:
            xg.XGError(maya.stringTable['y_xgDescriptionEditor.kYouMustSaveTheSceneFirst'])

        ExportStartFrame = float(pmc.playbackOptions(q=1, min=1))
        ExportEndFrame = float(pmc.playbackOptions(q=1, max=1))
        cmdAlembicBase = 'AbcExport -j "'

        cmdAlembicBase = cmdAlembicBase + '-frameRange ' + str(ExportStartFrame) + ' ' + str(ExportEndFrame)
        cmdAlembicBase = cmdAlembicBase + ' -uvWrite -attrPrefix xgen -worldSpace'
        palette = cmds.ls(exactType="xgmPalette")
        for p in range(len(palette)):
            filename = strScenePath + X + strSceneName + "__" + xgmExternalAPI.encodeNameSpace(str(palette[p])) + ".abc"
            descShapes = cmds.listRelatives(palette[p], type="xgmDescription", ad=True)
            cmdAlembic = cmdAlembicBase
            for d in range(len(descShapes)):
                descriptions = cmds.listRelatives(descShapes[d], parent=True)
                if len(descriptions):
                    patches = xg.descriptionPatches(descriptions[0])
                    for patch in patches:
                        cmd = 'xgmPatchInfo -p "' + patch + '" -g';
                        geom = mel.eval(cmd)
                        geomFullName = cmds.ls(geom, l=True)
                        cmdAlembic += " -root " + geomFullName[0]
            cmdAlembic = cmdAlembic + ' -stripNamespaces -file \'' + filename + '\'";';
            print cmdAlembic
            print 'export xgen patches ...'
            mel.eval(cmdAlembic)  

        print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\
@Export xgen patched is done!!!!!!!!!!!!!!!!!@\n\
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"

    @staticmethod
    def export_xgen_2ass(xgen_list, keyname) :  
        typelist = [str(pmc.PyNode(xgen).type()) for xgen in xgen_list]
        if "xgmDescription" in typelist :  
            nodeControl.old_xgen2patches()
        print typelist

    def getnodetype(self) :  
        return self.node.type()

    def getnodeparent(self) :  
        return self.node.listRelatives(parent=True)[0]

    def getnodechildren(self) :  
        return self.node.listRelatives(c=True)

    def export_cam(self, boolvalue, sf, ef, basepath) :  
        print boolvalue
        if boolvalue == True :  
            self.__exportCamera(basepath, sf, ef)
        elif boolvalue == False :  
            self.__exportCamera(basepath)

    def exportAbc(self, boolvalue, sf, ef, basepath, ccboolvalue) :  
        if boolvalue == True :  
            if ccboolvalue == True :  
                self.__exportCloth(basepath, "char", sf, ef)
                self.__exportAbc(basepath, "char", sf, ef)  
            else :  
                self.__exportAbc(basepath, "char", sf, ef)
        elif boolvalue == False :  
            if ccboolvalue == True :  
                self.__exportCloth(basepath, "char")
                self.__exportAbc(basepath, "char")  
            else :  
                self.__exportAbc(basepath, "char")

    def export_prop_abc(self, boolvalue, sf, ef, basepath) :  
        if boolvalue == True :  
            self.__exportAbc(basepath, "prop", sf, ef)
        elif boolvalue == False :  
            self.__exportAbc(basepath, "prop")

    @staticmethod
    def export_xgen(xgenlist, boolvalue, sf, ef, shadername, basepath) :  
        if boolvalue == True :  
            g_export_xgen(xgenlist, shadername, basepath, sf, ef)
        elif boolvalue == False :  
            g_export_xgen(xgenlist, shadername, basepath)

class fileSolver(object) :  
    def __init__(self, new_dir) :  
        self.dir = new_dir  
        self.mtime = os.path.getmtime(self.dir)  
        self.ctime = os.path.getctime(self.dir)  
        self.name = os.path.basename(self.dir)

    def getFileinfo(self) :  
        info_dict = {}  
        mtime = datetime.datetime.fromtimestamp(self.mtime)  
        ctime = datetime.datetime.fromtimestamp(self.ctime)  
        r_mtime = mtime.strftime('%Y-%m-%d %H:%M:%S')  
        r_ctime = mtime.strftime('%Y-%m-%d %H:%M:%S')  
        info_dict["name"] = self.name  
        info_dict["create_time"] = r_ctime  
        info_dict["change_time"] = r_mtime  
        return info_dict  

    def getchildren(self) :  
        children = os.listdir(self.dir)  
        return children  

class importer(object) :  
    def __init__(self, new_dir) :  
        self.dir = new_dir  
        self.char_dir = self.dir+X+"char"  
        self.cam_dir = self.dir+X+"Camera"  
        self.prop_dir = self.dir+X+"prop"  
        self.ass_dir = self.dir+X+"Assfile"
        self.dict_dir = self.dir+X+"Asset_list.json"
        self.material_dir = self.dir+X+"Material"
        self.reference_listFile = self.dir+X+"reference.txt"
        self.bg_dir = self.dir+X+"Bg"

    def showDir(self) :  
        print self.char_dir  
        print self.cam_dir  
        print self.prop_dir  
        print self.ass_dir  
        print self.dict_dir
        print self.material_dir

    def __import_char(self) :  
        if os.path.exists(self.char_dir) :  
            char_list = os.listdir(self.char_dir)  
            print char_list  
            for char in char_list :  
                charDir = self.char_dir + X + char  
                abc_file_list = os.listdir(charDir)  
                for abcFile in abc_file_list :  
                    abcDir = charDir + X + abcFile  
                    if abcDir.split("_")[-1] != "cloth.abc" :  
                        pmc.AbcImport(abcDir, mode='import')  

    def __import_cam(self) :  
        if os.path.exists(self.cam_dir) :  
            cam_list = os.listdir(self.cam_dir)  
            print cam_list
            for cam in cam_list :  
                camDir = self.cam_dir + X + cam  
                pmc.AbcImport(camDir, mode='import')  

    def __import_prop(self) :  
        if os.path.exists(self.prop_dir) :  
            prop_list = os.listdir(self.prop_dir)  
            print prop_list  
            for prop in prop_list :  
                propDir = self.prop_dir + X + prop  
                abc_file_list = os.listdir(propDir)  
                for abcFile in abc_file_list :  
                    abcDir = propDir + X + abcFile  
                    pmc.AbcImport(abcDir, mode='import')  

    def __import_Ass(self) :  
        if os.path.exists(self.ass_dir) :  
            ass_list = os.listdir(self.ass_dir)  
            if ass_list == [] :  
                pass
            # print ass_list
            else :  
                for ass in ass_list :  
                    assDir = self.ass_dir + X + ass  
                    if os.listdir(assDir) == [] :  
                        pass
                    else :  
                        ass_path = [i.split(".")[0] for i in os.listdir(assDir)]
                        ass_lst = list(set(ass_path))[0]
                        ass_full_path = assDir+X+ass_lst+".####.ass"
                        assNode = createStandIn(None)

                        tran_ass = assNode.listRelatives(fullPath=True, parent=True)[0]
                        tran_ass.rename(ass_lst)
                        print tran_ass

                        assNode.setAttr("dso", ass_full_path)
                        cmds.expression(o=assNode.name(), s="frameNumber=frame")
                self.__import_Hairshader()

    def __import_Hairshader(self) :  
        if os.path.exists(self.material_dir) :  
            mateiral_list = os.listdir(self.material_dir)
            for mat in mateiral_list :  
                if mat.split(".")[-1] == "mb" :  

                    print mat.split(".")[0]
                    if mat.split(".")[0] + "_" + mat.split(".")[0] in pmc.ls(type="reference") :  
                        print "shader is already in this scene..."  
                        pass  
                    else :  
                        matDir = self.material_dir+ X+ mat  
                        newnode = import_reference(matDir)

                        print newnode
                        for i in newnode :  
                            if pmc.PyNode(i).type() == "aiStandardHair" :  
                                assnodename = pmc.PyNode(i).name().split("_")[-1]+"SG"
                                print "Ass node name is :"
                                print assnodename
                                cmds.select(assnodename)
                                cmds.hyperShade( assign=i)

                        print "---end----"

    def __import_cloth(self) :  
        pass  

    def __import_mat(self) :  
        file = open(self.reference_listFile, "r")  
        path_list = file.readlines()  
        for i in path_list :  
            if platform.system() == "Linux" :  
                lnx_header = jiuqian_projectpath.split(X)  
                if i.startswith("Z:") :  
                    new_path = i.replace("Z:/project/film", jiuqian_projectpath)
                    if os.path.exists(new_path) :  
                        parent_path = X.join(new_path.split(X)[:-1])  
                        for path in os.listdir(parent_path+X+"shader") :  
                            if path.split("_")[-1] == "mat.mb" :  
                                print parent_path+X+path
                                mat_path = parent_path+X+"shader"+X+path  
                                # print mat_path
                                import_reference(mat_path)
                            else :  
                                print "-----------------------\nNo chr _sha\
                                       der.mb file\n-----------------------"
                else :  
                    print i
                    parent_path = X.join((i.split(X)[:-1]))  
                    for path in os.listdir(parent_path+X+"shader") :  
                        if path.split("_")[-1] == "mat.mb" :  
                            mat_path = parent_path+X+"shader"+X+path
                            if os.path.exists(mat_path) :  
                                import_reference(mat_path)
                        else :  
                            print "-----------------------\nNo chr _sha\
                                   der.mb file\n-----------------------"

            elif platform.system() == "Windows" :  
                windows_header = jiuqian_projectpath
                if i.startswith("/mnt/jiuqian/project/film") :  
                    new_path = i.replace("/mnt/jiuqian/project/film", jiuqian_projectpath)
                    if os.path.exists(new_path) :  
                        parent_path = X.join(new_path.split(X)[:-1])
                        for path in os.listdir(parent_path+X+"shader") :  
                            if path.split("_")[-1] == "mat.mb" :  
                                print parent_path+X+path
                                mat_path = parent_path+X+"shader"+X+path
                                import_reference(mat_path)
                            else :  
                                print "-----------------------\nNo chr _sha\
                               der.mb file\n-----------------------"
                        print i
                        parent_path = X.join((i.split(X)[:-1]))  
                        for path in os.listdir(parent_path+X+"shader") :  
                            if path.split("_")[-1] == "mat.mb" :  
                                mat_path = parent_path+X+"shader"+X+path
                                if os.path.exists(mat_path) :  
                                    import_reference(mat_path)
                            else :  
                                print "-----------------------\nNo chr _sha\
                               der.mb file\n-----------------------"
    def __import_bg(self) :  
        runtime = 0
        file = open(self.reference_listFile, "r")  
        path_list = file.readlines()  
        for i in path_list :  
            parent = X.join(i.split(X)[:-1])
            asset_type = X.join(parent.split(X)[:-1]).split("/")[-1]
            if asset_type == "bg" :  
                for i in os.listdir(parent) :  
                    if i.split("_")[-1] == "shader.mb" :  
                        runtime += 1
                        referencelist = [x.fileName(True, False, False) for x in pmc.ls(type="reference")]
                        print referencelist
                        if not parent+X+i in referencelist :  
                            import_reference(parent+X+i)
                        else :  
                            pass
                if runtime == 0 :   
                    print "-----------------------\nnot found %s\n-----------------------" % ("_".join(i.split("_")[0:-1])+"_shader.mb")
                else :  
                    pass
    def import_all(self) :  
        self.__import_char()  
        self.__import_prop()
        self.__import_cam()  
        self.__import_Ass()  
        # self.txt_resolve()
        self.__import_mat()
        import setSG
        setSG.abcLink()
        self.__import_bg()

